package com.i2works.smartluolong.manage.controller.admin;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.i2works.smartluolong.manage.entity.admin.AdminResDO;
import com.i2works.smartluolong.manage.entity.admin.AdminResQuery;
import com.i2works.smartluolong.manage.service.admin.IAdminResService;
import com.i2works.smartluolong.manage.utils.BaseModule;
import com.i2works.smartluolong.utils.common.BaseUtils;
import com.i2works.smartluolong.utils.base.URLConstant;
import com.i2works.smartluolong.utils.base.MsgEnum;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.entity.Tree;
import com.i2works.smartluolong.web.entity.common.TreeUtil;
import com.i2works.smartluolong.web.entity.user.UserResDO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 管理员资源
 *
 * @author koal <koal@vip.qq.com>
 * @ClassName: AdminResController
 * @date 2015年11月8日 上午2:16:43
 */
@Controller
@RequestMapping("/adminRes")
public class AdminResController extends BaseModule {

    private final IAdminResService adminResService;

    @Autowired
    public AdminResController(IAdminResService adminResService) {
        this.adminResService = adminResService;
    }

    /**
     * 系统管理资源页面
     */
    @RequestMapping(value = "/view/index")
    public String index() {
        logger.info("系统资源管理页面");
        return URLConstant.Admin.RES_URL;
    }


    /**
     * 无分页父类资源树
     *
     * @param showStatus：0显示所有的目录（不含按钮），1显示全部分类, 2显示所有正常父类
     */
    @RequestMapping(value = "/view/tree/{showStatus:^[0-2{1}]$}")
    @ResponseBody
    public List<Tree> queryTreeList(@PathVariable Integer showStatus) {
        List<Tree> result = Lists.newArrayList();
        try {
            AdminResQuery query = new AdminResQuery();
            query.setShowStatus(showStatus);
            List<AdminResDO> resList = adminResService.queryTreeList(query);
            List<Tree> treeDataList = Lists.newArrayList();
            for (AdminResDO adminRes : resList) {
                UserResDO userRes = new UserResDO();
                BeanUtils.copyProperties(adminRes, userRes);
                if (null != TreeUtil.resTree(userRes)) {
                    treeDataList.add(TreeUtil.resTree(userRes));
                }
            }
            result = TreeUtil.getNodeTree(0, treeDataList);
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }


    /**
     * 资源列表
     */
    @RequestMapping(value = "/view/api")
    @ResponseBody
    public Result queryList(@ModelAttribute AdminResQuery query) {
        Result result = new Result();
        try {
            int total = adminResService.queryCount(query);
            List<AdminResDO> queryAdminResList = Lists.newArrayList();
            if (total > 0) {
                queryAdminResList = adminResService.queryList(query);
            }
            result.setTotal(total);
            result.setRows(queryAdminResList);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.SYSTEM_ERROR.getMsg());
        }
        return result;
    }


    /**
     * 新增编辑系统资源跳转
     */
    @RequestMapping(value = "/save/form")
    public String savePage() {
        logger.info("系统资源新增编辑");
        return URLConstant.Admin.RES_FORM_URL;
    }


    /**
     * 添加系统资源
     */
    @RequestMapping(value = "/save/action", method = RequestMethod.POST)
    @ResponseBody
    public Result save(@ModelAttribute AdminResDO adminRes) {
        Result result = new Result();
        try {
            List<Integer> keyList = Lists.newArrayList();
            if (adminRes.getPid() == null) {
                adminRes.setPid(0);
            }
            Integer temp = adminRes.getPid();
            /**
             * 得到传递的父类ID，然后得到父类ID，并绑定到keyList和设置temp为父类ID
             * 把temp的父类ID当成ID，循环到上一级父类....
             */
            if (temp != 0) {
                for (; ; ) {
                    AdminResQuery query = new AdminResQuery();
                    query.setId(temp);
                    AdminResDO res = adminResService.query(query);
                    //如果PID等于0，说明上级是根路径，就不循环，如果不等于0，设置temp为PID在循环上一层
                    //复制父类ID
                    keyList.add(res.getId());
                    if (res.getPid() == 0) {
                        break;
                    } else if (res.getPid() != 0) {
                        //设置temp的ID是父类ID
                        temp = res.getPid();
                    }
                }
                //排列得到的结果
                adminRes.setResKey(BaseUtils.sortListToStr(keyList));
            } else {
                //排列得到的结果
                adminRes.setResKey("0");
            }
            adminRes.setUpdateName(getUserName());
            adminResService.save(adminRes);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.SAVE_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 查询某个资源
     */
    @RequestMapping(value = "/view/{id}")
    @ResponseBody
    public Result query(@PathVariable Integer id) {
        Result result = new Result();
        try {
            AdminResQuery query = new AdminResQuery();
            query.setId(id);
            AdminResDO adminRes = adminResService.query(query);
            result.setModel(adminRes);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.FIND_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 返回已选的资源数据
     */
    @RequestMapping(value = "/view/hasCheck", method = RequestMethod.POST)
    @ResponseBody
    public Result queryHasChecked(@RequestParam(value = "roleId", required = false) Integer roleId, HttpServletRequest request) {
        Result result = new Result();
        try {
            AdminResQuery query = new AdminResQuery();
            if (roleId != null) {
                query.setRoleId(roleId);
                AdminResDO adminResDO = adminResService.queryHasChecked(query);
                JSONObject json = new JSONObject();
                json.put("ids", adminResDO.getIds());
                json.put("names", adminResDO.getNames());
                result.setModel(json);
            }
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.FIND_ERROR.getMsg());
        }
        return result;
    }


    /**
     * 某个系统资源（名称、标示、代码）是否存在验证
     */
    @RequestMapping(value = "/view/check", method = RequestMethod.POST)
    @ResponseBody
    public boolean queryCheck(@ModelAttribute AdminResQuery query) {
        boolean result = false;
        try {
            int count = adminResService.queryCheck(query);
            if (count <= 0) {
                result = true;
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }

    /**
     * 更新资源状态
     */
    @RequestMapping(value = "/status/action", method = RequestMethod.POST)
    @ResponseBody
    public Result updateStatus(@ModelAttribute AdminResDO adminRes) {
        Result result = new Result();
        try {
            adminRes.setUpdateName(getUserName());
            adminResService.updateStatus(adminRes);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.STATUS_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 更新资源状态
     * 备注：附带更新角色与资源的关联表状态
     */
    @RequestMapping(value = "/status/batchAction", method = RequestMethod.POST)
    @ResponseBody
    public Result updateBatchStatus(@RequestParam("idsList[]") List<Integer> idsList, Integer status) {
        Result result = new Result();
        try {
            if (idsList != null && idsList.size() > 0) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("idsList", idsList);
                map.put("updateName", getUserName());
                map.put("status", status);
                adminResService.updateBatchStatus(map);
            }
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.STATUS_ERROR.getMsg());
        }
        return result;
    }


    /**
     * 用户下拉资源列表
     */
    @RequestMapping(value = "/view/resSelect")
    @ResponseBody
    public Result querySelect(@ModelAttribute AdminResQuery query) {
        Result result = new Result();
        try {
            query.setStatus(1);//只显示启用的
            query.setLimit(100L);
            query.setResType(1);
            List<AdminResDO> resSelect = adminResService.querySelect(query);
            result.setTotal(resSelect.size());
            result.setRows(resSelect);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.SYSTEM_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 删除
     *
     * @param id
     * @return result
     */
    @RequestMapping(value = "/delete/action", method = RequestMethod.POST)
    @ResponseBody
    public Result delete(@RequestParam Integer id) {
        Result result = new Result();
        try {
            adminResService.delete(id);
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.DELETE_ERROR.getMsg());
        }
        return result;
    }

    /**
     * 批量删除
     *
     * @param idsList
     * @return result
     */
    @RequestMapping(value = "/delete/batchAction", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteBatch(@RequestParam("idsList[]") List<Integer> idsList) {
        Result result = new Result();
        try {
            if (idsList != null && idsList.size() > 0) {
                adminResService.deleteBatch(idsList);
            }
        } catch (Exception e) {
            logger.error("", e);
            result.setSuccess(false);
            result.setMsg(MsgEnum.DELETE_ERROR.getMsg());
        }
        return result;
    }
}
